# -*- coding: utf-8 -*-

import sys
import win32print
import win32api
import sqlite3
import zbar
from PIL import Image as pil_image
from PyQt4 import QtCore,QtGui
import cv2
import numpy as np

#pdf生成库
#用于定位的inch库，inch将作为我们的高度宽度的单位
from reportlab.lib.units import inch,cm
from reportlab.lib.pagesizes import letter,A4
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
#中文字体注册
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
pdfmetrics.registerFont(TTFont('song', 'simsunb.ttf'))
pdfmetrics.registerFont(TTFont('hei', 'simhei.ttf'))
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))


from QRcodeWin import Ui_MainWindow

class QRcodeWindow(QtGui.QMainWindow):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #QtCore.QObject.connect(self.ui.actionYunxing, QtCore.SIGNAL("triggered()"), self.run)
        self.ui.tableWidget_table.setColumnCount(6)
        self.ui.tableWidget_table.setColumnWidth(0, 40)
        self.ui.tableWidget_table.setColumnWidth(1, 60)
        self.ui.tableWidget_table.setColumnWidth(2, 100)
        self.ui.tableWidget_table.setColumnWidth(3, 150)
        self.ui.tableWidget_table.setColumnWidth(4, 150)
        self.ui.tableWidget_table.setColumnWidth(5, 80)
        #self.ui.tableWidget_table.setRowCount(6)
        self.ui.tableWidget_table.setHorizontalHeaderLabels([u'编码',u'姓名',u'电话',u'邮箱',u'单位',u'职务'])
        #self.ui.label_image.setPixmap(QtGui.QPixmap("qr_code.png").scaled(self.ui.label_image.size(), QtCore.Qt.KeepAspectRatio,QtCore.Qt.SmoothTransformation))
        #self.ui.label_image.setPixmap(QtGui.QPixmap("qr_code.png").scaled( QtCore.QSize(670,550), QtCore.Qt.KeepAspectRatio,QtCore.Qt.SmoothTransformation))
        self.ui.label_image.repaint()
        QtCore.QObject.connect(self.ui.pushButton_chaxun, QtCore.SIGNAL("clicked()"), self.querySql)
        QtCore.QObject.connect(self.ui.pushButton_print, QtCore.SIGNAL("clicked()"), self.pdf_print)
        QtCore.QObject.connect(self.ui.pushButton_CXandPRT, QtCore.SIGNAL("clicked()"), self.sql_manage)
        QtCore.QObject.connect(self.ui.pushButton_config, QtCore.SIGNAL("clicked()"), self.config)
        #QtCore.QObject.connect(self.ui.lineEdit_code, QtCore.SIGNAL("textChanged(const QString &)"), self.textChange)


    def sql_manage(self):
        import os
        cur_path = os.getcwd()
        exe_path = cur_path+"\\SQLiteStudio\\SQLiteStudio.exe"
        exe_path = str(exe_path)
        win32api.ShellExecute(0,'open', exe_path, None, ".", True)
        #ShellExecute(NULL,"open","calc.exe",NULL,NULL,SW_SHOWNORMAL);

    def config(self):
        import os
        cur_path = os.getcwd()
        config_path = cur_path+"\\config.ini"
        config_path = str(config_path)
        win32api.ShellExecute(0, 'open', 'notepad.exe', config_path, ".", True)
        #ShellExecute(NULL,"open","calc.exe",NULL,NULL,SW_SHOWNORMAL);

    def querySql(self):
        #连接数据库
        db_file = "iosrts2017.db"
        conn = sqlite3.connect(db_file)
        cu = conn.cursor()

        header = ""
        if self.ui.checkBox_QR.checkState() == QtCore.Qt.Checked:
            self.ui.lineEdit_code.setText(QtCore.QString(""))#清空
            self.scanAndDetect()
            txt = self.ui.lineEdit_code.text()
            txt = str(txt)
            ind = txt.find("?id=")
            if ind == -1:
                return
            else:
                sql_id = txt[ind+4:]
                strSql = "SELECT zw_user.id,zw_userinfo.name,zw_userinfo.phone,zw_user.email, zw_userinfo.institution,zw_userinfo.edu\
                                                            FROM zw_user\
                                                            LEFT JOIN zw_userinfo ON zw_user.id = zw_userinfo.uid\
                                                            WHERE zw_user.id = '%s'" % (sql_id)
                cu.execute(strSql)
            header = "二维码"
        #数据库查询
        elif self.ui.checkBox_name.checkState() == QtCore.Qt.Checked:
            if self.ui.lineEdit_name.text() != None:
                strSql = "SELECT zw_user.id,zw_userinfo.name,zw_userinfo.phone,zw_user.email, zw_userinfo.institution,zw_userinfo.edu\
                                            FROM zw_user\
                                            LEFT JOIN zw_userinfo ON zw_user.id = zw_userinfo.uid\
                                            WHERE zw_userinfo.name = '%s'" % (self.ui.lineEdit_name.text(),)
                cu.execute(strSql)
                header = u"姓名"
        elif self.ui.checkBox_tel.checkState() == QtCore.Qt.Checked:
            if self.ui.lineEdit_tel.text() != None:
                strSql = "SELECT zw_user.id,zw_userinfo.name,zw_userinfo.phone,zw_user.email, zw_userinfo.institution,zw_userinfo.edu\
                                            FROM zw_user\
                                            LEFT JOIN zw_userinfo ON zw_user.id = zw_userinfo.uid\
                                            WHERE zw_userinfo.phone = '%s'" % (self.ui.lineEdit_tel.text(),)
                cu.execute(strSql)
                header = u"电话"
        elif self.ui.checkBox_email.checkState() == QtCore.Qt.Checked:
            if self.ui.lineEdit_email.text() != None:
                strSql = "SELECT zw_user.id,zw_userinfo.name,zw_userinfo.phone,zw_user.email, zw_userinfo.institution,zw_userinfo.edu\
                                            FROM zw_user\
                                            LEFT JOIN zw_userinfo ON zw_user.id = zw_userinfo.uid\
                                            WHERE zw_user.email = '%s'" % (self.ui.lineEdit_email.text(),)
                cu.execute(strSql)
                header = u"邮箱"
        else:
            strSql = "SELECT zw_user.id,zw_userinfo.name,zw_userinfo.phone,zw_user.email, zw_userinfo.institution,zw_userinfo.edu\
                                                        FROM zw_user\
                                                        LEFT JOIN zw_userinfo ON zw_user.id = zw_userinfo.uid"
            cu.execute(strSql)
        #显示列表
        ret_list = cu.fetchall()
        import win32ui
        import ctypes
        win = ctypes.windll.LoadLibrary("user32.dll")
        if len(ret_list) == 0:
            if self.ui.checkBox_name.checkState() == QtCore.Qt.Checked:
                #win32ui.MessageBox(u"%s:%s,查无此人！"%(header,self.ui.lineEdit_name.text(),))
                win.MessageBoxW(None, u"%s:%s,查无此人！"%(header,self.ui.lineEdit_name.text(),), u'提示信息', 0)
            elif self.ui.checkBox_tel.checkState() == QtCore.Qt.Checked:
                #win32ui.MessageBox(u"%s:%s,查无此号！" % (header, self.ui.lineEdit_tel.text(),))
                win.MessageBoxW(None, u"%s:%s,查无此号！" % (header, self.ui.lineEdit_tel.text(),), u'提示信息', 0)
            elif self.ui.checkBox_email.checkState() == QtCore.Qt.Checked:
                #win32ui.MessageBox(u"%s:%s,查无此项！" % (header, self.ui.lineEdit_email.text(),))
                win.MessageBoxW(None, u"%s:%s,查无此项！" % (header, self.ui.lineEdit_email.text(),), u'提示信息', 0)
            return
        elif len(ret_list) == 1:
            self.ui.tableWidget_table.setColumnCount(2)#列
            self.ui.tableWidget_table.setColumnWidth(0, 100)
            self.ui.tableWidget_table.setColumnWidth(1, 380)
            self.ui.tableWidget_table.setHorizontalHeaderLabels([u'项目', u'名称'])
            self.ui.tableWidget_table.setRowCount( 6 )#行
            items = [u'编码', u'姓名', u'电话', u'邮箱', u'单位', u'职务']
            descr = ret_list[0]
            newItem01 = QtGui.QTableWidgetItem("%s" % items[0])
            self.ui.tableWidget_table.setItem(0, 0, newItem01)
            newItem02 = QtGui.QTableWidgetItem("%s" % descr[0])
            self.ui.tableWidget_table.setItem(0, 1, newItem02)
            newItem03 = QtGui.QTableWidgetItem("%s" % items[1])
            self.ui.tableWidget_table.setItem(1, 0, newItem03)
            newItem04 = QtGui.QTableWidgetItem("%s" % descr[1])
            self.ui.tableWidget_table.setItem(1, 1, newItem04)
            newItem05 = QtGui.QTableWidgetItem("%s" % items[2])
            self.ui.tableWidget_table.setItem(2, 0, newItem05)
            newItem06 = QtGui.QTableWidgetItem("%s" % descr[2])
            self.ui.tableWidget_table.setItem(2, 1, newItem06)
            newItem01 = QtGui.QTableWidgetItem("%s" % items[3])
            self.ui.tableWidget_table.setItem(3, 0, newItem01)
            newItem02 = QtGui.QTableWidgetItem("%s" % descr[3])
            self.ui.tableWidget_table.setItem(3, 1, newItem02)
            newItem03 = QtGui.QTableWidgetItem("%s" % items[4])
            self.ui.tableWidget_table.setItem(4, 0, newItem03)
            newItem04 = QtGui.QTableWidgetItem("%s" % descr[4])
            self.ui.tableWidget_table.setItem(4, 1, newItem04)
            newItem05 = QtGui.QTableWidgetItem("%s" % items[5])
            self.ui.tableWidget_table.setItem(5, 0, newItem05)
            newItem06 = QtGui.QTableWidgetItem("%s" % descr[5])
            self.ui.tableWidget_table.setItem(5, 1, newItem06)
        else:
            self.ui.tableWidget_table.setColumnCount(6)
            self.ui.tableWidget_table.setColumnWidth(0, 40)
            self.ui.tableWidget_table.setColumnWidth(1, 60)
            self.ui.tableWidget_table.setColumnWidth(2, 100)
            self.ui.tableWidget_table.setColumnWidth(3, 150)
            self.ui.tableWidget_table.setColumnWidth(4, 150)
            self.ui.tableWidget_table.setColumnWidth(5, 80)
            # self.ui.tableWidget_table.setRowCount(6)
            self.ui.tableWidget_table.setHorizontalHeaderLabels([u'编码', u'姓名', u'电话', u'邮箱', u'单位', u'职务'])
            self.ui.tableWidget_table.setRowCount( len( ret_list ) )
            i,j = 0,0
            for line in ret_list:
                newItem01 = QtGui.QTableWidgetItem("%d" % line[0])
                self.ui.tableWidget_table.setItem(i, 0, newItem01)
                newItem02 = QtGui.QTableWidgetItem("%s" % line[1])
                self.ui.tableWidget_table.setItem(i, 1, newItem02)
                newItem03 = QtGui.QTableWidgetItem("%s" % line[2])
                self.ui.tableWidget_table.setItem(i, 2, newItem03)
                newItem04 = QtGui.QTableWidgetItem("%s" % line[3])
                self.ui.tableWidget_table.setItem(i, 3, newItem04)
                newItem05 = QtGui.QTableWidgetItem("%s" % line[4])
                self.ui.tableWidget_table.setItem(i, 4, newItem05)
                newItem06 = QtGui.QTableWidgetItem("%s" % line[5])
                self.ui.tableWidget_table.setItem(i, 5, newItem06)
                i = i+1

        #格式化pdf文件和jpg图片
        ll = ret_list[0]  # 临时，只取第一条结果

        cn_name = ll[1]  # 名字
        unit = ll[1]  # 单位
        degree = ll[2]  # 学位
        cn_iosrts = u"国际溢油应急研讨会2017"
        en_iosrts = "International Oil Spill Response Seminar 2017"
        time_iosrts = "18-22 Sept. 2017"
        type_person = u"参会人员"

        doc = SimpleDocTemplate("Chest_card.pdf", pagesize=(9.2 * cm, 12.4 * cm), rightMargin=0.5 * cm,
                                leftMargin=0.5 * cm, topMargin=0, bottomMargin=0)
        Story = []
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))

        # 会议标题
        Story.append(Spacer(1, 0.8 * cm))  # 设计空行
        from reportlab.lib.enums import TA_LEFT, TA_CENTER
        ptext = '<para align=center spaceb=3><font size=18> %s </font></para>' % cn_iosrts
        Story.append(Paragraph(ptext, ParagraphStyle(name='Normal',
                                                     fontName='hei',
                                                     fontSize=18,
                                                     leading=12, alignment=TA_CENTER)))
        # 会议标题-英文
        Story.append(Spacer(1, 0.5 * cm))  # 设计空行
        ptext = '<font size=13> %s </font>' % en_iosrts
        # Story.append(Paragraph(ptext, styles["Title"]))
        # 参考Title的源码设定
        # stylesheet.add(ParagraphStyle(name='Title',
        #                               parent=stylesheet['Normal'],
        #                               fontName=_baseFontNameB,
        #                               fontSize=18,
        #                               leading=22,
        #                               alignment=TA_CENTER,
        #                               space
        Story.append(Paragraph(ptext, ParagraphStyle(name='Title',
                                                     fontName='Helvetica',
                                                     fontSize=14,
                                                     leading=18,
                                                     eading=22,
                                                     alignment=TA_CENTER)))
        # 时间
        Story.append(Spacer(1, 2.0 * cm))  # 设计空行
        ptext = '<para align=center><font size=12>%s</font></para>' % time_iosrts
        Story.append(Paragraph(ptext, styles["Normal"]))
        Story.append(Spacer(1, 1.5 * cm))
        # 姓名中文
        ptext = '<para align=center spaceb=3><font size=18> %s </font></para>' % cn_name
        Story.append(Paragraph(ptext, ParagraphStyle(name='Normal',
                                                     fontName='hei',
                                                     fontSize=18,
                                                     leading=12)))
        #二维码图片
        Story.append(Spacer(1, 1.3 * cm))
        img = Image("footewm.png", width=2*cm, height=2*cm)
        img.hAlign = 'CENTER'
        Story.append(img)

        # 类型
        Story.append(Spacer(1, 0.1* cm))
        ptext = '<para align=center spaceb=3><b><font size=18> %s </font></b></para>' % type_person
        Story.append(Paragraph(ptext, ParagraphStyle(name='Normal',
                                                     fontName='hei',
                                                     fontSize=18,
                                                     leading=12, alignment=TA_CENTER)))

        doc.build(Story)
        #pdf转为图片
        import sys
        import PyPDF2
        import PythonMagick
        i_file = "Chest_card.pdf"  # 输入文件，pdf
        o_dire = "Chest_card.jpg"  # 输出图片，写死为jpg格式
        ds = 180  # 图片分辨率
        image = PythonMagick.Image()
        image.density(str(ds))
        image.read(i_file + '[' + '0' + ']')#第一页
        image.magick("JPG")
        image.write(o_dire)
        #显示图片
        import time
        time.sleep(1.0)#延时1秒
        self.ui.label_image.setAlignment(QtCore.Qt.AlignCenter)
        self.ui.label_image.setPixmap(
            QtGui.QPixmap("Chest_card.jpg").scaled(QtCore.QSize(500, 700), QtCore.Qt.KeepAspectRatio,
                                                QtCore.Qt.SmoothTransformation))

    def pdf_print(self):
        import win32print
        import win32api

        # 罗列当前打印机列表,返回(flags, description, name, comment)
        list_printers = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL)
        # 选择打印机
        printer_name = list_printers[2][2]
        # 打开打印机
        hPrinter = win32print.OpenPrinter(printer_name)
        # printer_name = win32print.GetDefaultPrinter()

        in_file = "Chest_card.pdf"
        fp = open(in_file, 'r')
        win32api.ShellExecute(0,
                              "print",
                              in_file,
                              '"%s"' % win32print.GetDefaultPrinter(),
                              ".",
                              0)
        #win32api.ShellExecute(0, "print", in_file, None, ".", 0)

    def show_img(self, filename, ctrlName):#显示图片,ctrlName为要显示图片空间的名称
        #存在安全问题
        eval(ctrlName+".setText('')")
        eval(ctrlName+".setPixmap(QtGui.QPixmap(filename).scaled(self.ui.img_sw01.size(),QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation))")
        #exeline = ctrlName+"_txt"+".setText('%s'.decode('utf-8'))"%imgTip
        #eval(exeline)
        eval(ctrlName + ".repaint()")

    def detect(self,image):
        # convert the image to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        # compute the Scharr gradient magnitude representation of the images
        # in both the x and y direction
        gradX = cv2.Sobel(gray, ddepth=cv2.cv.CV_32F, dx=1, dy=0, ksize=-1)
        gradY = cv2.Sobel(gray, ddepth=cv2.cv.CV_32F, dx=0, dy=1, ksize=-1)
        # subtract the y-gradient from the x-gradient
        gradient = cv2.subtract(gradX, gradY)
        gradient = cv2.convertScaleAbs(gradient)
        # blur and threshold the image
        blurred = cv2.blur(gradient, (9, 9))
        (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
        # construct a closing kernel and apply it to the thresholded image
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
        closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
        # perform a series of erosions and dilations
        closed = cv2.erode(closed, None, iterations=4)
        closed = cv2.dilate(closed, None, iterations=4)
        # find the contours in the thresholded image
        (cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
                                     cv2.CHAIN_APPROX_SIMPLE)
        # if no contours were found, return None
        if len(cnts) == 0:
            return None
        # otherwise, sort the contours by area and compute the rotated
        # bounding box of the largest contour
        c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
        rect = cv2.minAreaRect(c)
        box = np.int0(cv2.cv.BoxPoints(rect))
        # return the bounding box of the barcode
        return box

    def scanAndDetect(self):
        # create a reader
        scanner = zbar.ImageScanner()
        # configure the reader
        scanner.parse_config('enable')
        font = cv2.FONT_HERSHEY_SIMPLEX
        camera = cv2.VideoCapture(0)
        while True:
            # grab the current frame
            (grabbed, frame) = camera.read()
            # check to see if we have reached the end of the
            # video
            if not grabbed:
                break
            # detect the barcode in the image
            box = self.detect(frame)
            if box != None:
                min = np.min(box, axis=0)
                max = np.max(box, axis=0)
                roi = frame[min[1] - 10:max[1] + 10, min[0] - 10:max[0] + 10]
                print roi.shape
                roi = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
            pil = pil_image.fromarray(frame).convert('L')
            width, height = pil.size
            raw = pil.tobytes()
            # wrap image data
            zarimage = zbar.Image(width, height, 'Y800', raw)
            # scan the image for barcodes
            scanner.scan(zarimage)
            # extract results
            for symbol in zarimage:
                # do something useful with results
                print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
                cv2.drawContours(frame, [box], -1, (0, 255, 0), 2)
                cv2.putText(frame, symbol.data, (20, 100), font, 1, (0, 255, 0), 4)
                self.ui.lineEdit_code.setText( QtCore.QString("%s"%symbol.data) )
            # if a barcode was found, draw a bounding box on the frame
            # show the frame and record if the user presses a key
            cv2.imshow("Frame", frame)
            key = cv2.waitKey(1) & 0xFF
            # if the 'q' key is pressed, stop the loop
            #if key == ord("q"):
            if key == 27:
                break
            #模拟键盘输出Esc，键值为：27
            ret = self.ui.lineEdit_code.text()
            import win32api, win32con
            if len(ret)>10:
                win32api.keybd_event(27, 0, 0, 0)  # v键位码是81
                win32api.keybd_event(27, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键
        # cleanup the camera and close any open windows
        camera.release()
        cv2.destroyAllWindows()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = QRcodeWindow()
    myapp.show()
    sys.exit(app.exec_())